package com.tongtailian.www.stir.activity;

import android.androidlib.ui.view.alertview.AlertView;
import android.androidlib.ui.view.alertview.OnItemClickListener;
import android.androidlib.utils.ACache;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Parcel;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.clj.fastble.data.BleDevice;
import com.hcb.logsdk.manager.LOGSDKManager;
import com.hcb.logsdk.service.PushLogService;
import com.hcb.logsdk.util.L;
import com.tongtailian.www.stir.MyApplication;
import com.tongtailian.www.stir.R;
import com.tongtailian.www.stir.adapter.HomeSampleAdapter;
import com.tongtailian.www.stir.base.BaseActivity;
import com.tongtailian.www.stir.bean.ConfigBean;
import com.tongtailian.www.stir.bean.ConfigDataFram;
import com.tongtailian.www.stir.bean.DeviceStateFram;
import com.tongtailian.www.stir.bean.NumberBean;
import com.tongtailian.www.stir.bleinterface.MyBleDeviceStateCallBack;
import com.tongtailian.www.stir.bleinterface.MyBleGattCallback;
import com.tongtailian.www.stir.comm.Observer;
import com.tongtailian.www.stir.comm.ObserverManager;
import com.tongtailian.www.stir.fragment.MyDialogFragment;
import com.tongtailian.www.stir.utils.BleManageUtil;
import com.tongtailian.www.stir.utils.LogUtil;
import com.tongtailian.www.stir.utils.ParcelableUtil;
import com.tongtailian.www.stir.utils.PushLog;
import com.tongtailian.www.stir.utils.SoundPlayer;
import com.tongtailian.www.stir.utils.ToastUtils;
import com.tongtailian.www.stir.utils.gson.GsonUtil;
import com.tongtailian.www.stir.view.CircleLayout;

import java.util.ArrayList;
import java.util.List;

import me.jessyan.autosize.AutoSizeCompat;

public class MainActivity extends BaseActivity implements View.OnClickListener, Observer {

    private TextView btHelp;
    private TextView btSlectParame;
    private long firstTime = 0;

    //    private Button blueTooth;
    private SeekBar progressBar;
    private RelativeLayout rlBegin;
    private ImageView ivPlay;
    private TextView tvCurrentSample;
    private TextView tvSampleBat;
    private RecyclerView recycleviewWorking;
    private HomeSampleAdapter homeSampleAdapter;
    private ImageView ivMore;
    private LinearLayout llBluetoochSetting;
    private ImageView ivPlayState;
    private LinearLayout llPlay;
    private CircleLayout circlelayout;


    private List<NumberBean> demoLocationList = new ArrayList<>();//样品数量
    private List<NumberBean> runningDemoLocationList = new ArrayList<>();//样品数量
    private List<ConfigBean> circleStateList = new ArrayList<>();
    private BleManageUtil bleManageUtil;
    private TextView tvMode;
    private MyDialogFragment myDialogFragment;

    private CountDownTimer timer;//定时器查询工作状态
    private String locationList;
    private int dataDev;
    private int flow;

    private int doingIndex = -1;
    private int oldDoingIndex = -1;
    private Chronometer chronometer;
    private SoundPlayer soundPlayer;

    ACache aCache;
    private BleDevice cacheBleDevice;

    private TextView tv_group_custom,tv_group_default,tv_changee_knife,tv_loop_num,tv_wish_pipe,tv_wish_knife;
    private boolean isWhisKnife;
    private boolean isWhisPipe;
    private boolean isChangeKnife;
    private int name;

    String nameArray[] = {"根茎类", "叶菜类", "花果菜类", "干果类", "水果类", "谷物类", "鱼肉类", "其他类"};
    String valueArray[] = {"样品重量≤500克，如：萝卜、胡萝卜、豆薯、甘薯、主要有莴笋、茎用芥菜、球茎甘蓝、竹笋、土豆、莲藕、洋葱、大蒜等。",
            "样品重量≤500克，如：白菜、菠菜、苋菜、莴苣、韭菜、芹菜等",
            "样品重量≤500克，如：金针菜、花椰菜、紫菜薹、南瓜、黄瓜、冬瓜、丝瓜、番茄、辣椒、茄子、豆角等",
            "样品重量≤500克，如：杏仁、腰果、榛子、核桃、板栗、白果、花生、葵花子、南瓜子、板栗、杏仁等（坚果类需去壳）",
            "样品重量≤500克，如：草莓、蓝莓、覆盆子、橘子、柠檬、柚子、葡萄、桃、枣、龙眼、荔枝、苹果、梨、柿子等",
            "样品重量≤500克，如：薏米、高梁、大麦、糙米、红小豆、小米、黑豆、黄豆等",
            "样品重量≤500克，如：活鱼、虾、海鲜、牛肉、羊肉、猪肉。含内脏含熟食",
            "样品重量≤500克，难处理的样品：粉丝、西兰花、蒜苗等"};
    private List<ConfigBean> runTypelist = new ArrayList<>();//研磨模式
    private int loopNum = 1;
    private int curLoopNum = 1;
    private boolean isLoop;
    private AlertView mHistoryAlertView;

    private ImageView iv_group_custom_state,iv_group_state;

    @Override
    public int setLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initVariables() {
        setTitle("TTL-500型全自动刀式研磨仪");
        //选中几号 座机位
        locationList = spManager.getLocationList();
        soundPlayer = new SoundPlayer(this);
    }


    @Override
    public void initViews(Bundle savedInstanceState) {

        circlelayout = findViewById(R.id.circlelayout);
        bleManageUtil = BleManageUtil.getInstance();//初始化蓝牙
        btHelp = findViewById(R.id.bt_help);
        btSlectParame = findViewById(R.id.bt_slect_parame);

        tvMode = findViewById(R.id.tv_mode);
        rlBegin = (RelativeLayout) findViewById(R.id.rl_begin);
        ivPlay = (ImageView) findViewById(R.id.iv_play);
        tvCurrentSample = findViewById(R.id.tv_current_sample);

        ivMore = findViewById(R.id.iv_more);
        iv_group_custom_state = findViewById(R.id.iv_group_custom_state);
        iv_group_state = findViewById(R.id.iv_group_state);

        llBluetoochSetting = findViewById(R.id.ll_bluetooch_setting);
        ivPlayState = findViewById(R.id.iv_play_state);
        llPlay = findViewById(R.id.ll_play);
        chronometer = findViewById(R.id.chronometer);

        btHelp.setOnClickListener(this);
        ivMore.setOnClickListener(this);
        btSlectParame.setOnClickListener(this);
        llBluetoochSetting.setOnClickListener(this);
        llPlay.setOnClickListener(this);

        tvSampleBat = findViewById(R.id.tv_sample_bat);

        progressBar = findViewById(R.id.progressBar);
        progressBar.setEnabled(false);
        llLeft.setVisibility(View.GONE);


        tv_group_custom = findViewById(R.id.tv_group_custom);
        tv_group_default = findViewById(R.id.tv_group_default);
        tv_changee_knife = findViewById(R.id.tv_changee_knife);
        tv_loop_num = findViewById(R.id.tv_loop_num);
        tv_wish_pipe = findViewById(R.id.tv_wish_pipe);
        tv_wish_knife = findViewById(R.id.tv_wish_knife);


        tv_group_custom.setOnClickListener(this);
        tv_group_default.setOnClickListener(this);
        tv_changee_knife.setOnClickListener(this);
        tv_loop_num.setOnClickListener(this);
        tv_wish_pipe.setOnClickListener(this);
        tv_wish_knife.setOnClickListener(this);


        initData();

        ObserverManager.getInstance().addObserver(this);
    }

    private void initData() {

        for (int i = 0; i < 4; i++) {
            ConfigBean configBean = new ConfigBean();
            configBean.setState(0);
            circleStateList.add(configBean);
        }

        try {
            getLocationBlue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (cacheBleDevice != null) {
            if (!BleManageUtil.getInstance().isConnect)
                showHistoryConnectDialog("检测到历史连接记录,是否重新连接?", cacheBleDevice);
        }else{
            if (myDialogFragment == null) {
                showBlueToochFragment();
            }
        }
    }


    private BleDevice getLocationBlue() {
        aCache = ACache.get(this);
        byte[] bluetooth = aCache.getAsBinary("Bluetooth");
        Parcel unmarshall = ParcelableUtil.unmarshall(bluetooth);
        cacheBleDevice = null;
        cacheBleDevice = BleDevice.CREATOR.createFromParcel(unmarshall);
        return cacheBleDevice;
    }


    @Override
    public void doBusiness() {

        initPermissions();
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "当前设备不支持BLE蓝牙4.0", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        updateList();
        updategroupList();

        bleManageUtil.initData(this);
        updateCircleLocation();

    }

    private void updateList(){
        String runType = spManager.getRunType();
        LogUtil.d("获取的runType = " + locationList);
        LogUtil.d("nameArray.length = "+nameArray.length);
        if (TextUtils.isEmpty(runType)) {
            for (int i = 1; i <= 63; i++) {
                ConfigBean bean = new ConfigBean();

                if (i <= nameArray.length) {
                    bean.setLook("查看");
                    bean.setEdit(false);
                    bean.setName(nameArray[i - 1]);
                    bean.setValue(valueArray[i - 1]);
                } else {
                    bean.setLook("编辑");
                    bean.setEdit(true);
                    bean.setName("自定义" + String.valueOf(i - 1));
                }
                bean.setSelect(false);
                runTypelist.add(bean);
            }
            LogUtil.d("保存的 = " + GsonUtil.gsonString(runTypelist));
            spManager.saveRunType(GsonUtil.gsonString(runTypelist));
        } else {
            runTypelist = GsonUtil.jsonToList(runType, ConfigBean.class);
            LogUtil.d("获取的的 = " + GsonUtil.gsonString(runTypelist));
        }
    }

    public void updategroupList(){
        locationList = spManager.getLocationList();
        LogUtil.d("locationList = " + locationList);
        if (TextUtils.isEmpty(locationList)) {
            for (int i = 1; i <= 4; i++) {
                NumberBean bean = new NumberBean();
                bean.setName(String.valueOf(i) + "号");
                bean.setGroup_name("根茎类");
                bean.setGroup(0);
                bean.setSelect(true);
                demoLocationList.add(bean);
            }
            spManager.saveLocationList(GsonUtil.gsonString(demoLocationList));
        } else {
            demoLocationList = GsonUtil.jsonToList(locationList, NumberBean.class);
        }
    }

    private void timeRestart() {
        chronometer.setBase(SystemClock.elapsedRealtime());
        //设置起始时间和时间格式，然后开始计时
        chronometer.setFormat("已用时间：%s");
        chronometer.start();
    }

    private void timeStop() {
        chronometer.stop();
    }


    //设置圆圈背景
    private void updateCircleLocation() {
        LogUtil.d("locationList = " + locationList);
        LogUtil.d("circlelayout.getChildCount()  = " + circlelayout.getChildCount());
        //选中几号 座机位
        locationList = spManager.getLocationList();
        if (!TextUtils.isEmpty(locationList)) {
            demoLocationList = GsonUtil.jsonToList(locationList, NumberBean.class);
            for (int i = 0; i < circlelayout.getChildCount(); i++) {
                View childAt = circlelayout.getChildAt(i);

                NumberBean numberBean;
                boolean b;
                if (childAt != null) {
                    LogUtil.d("doingIndex = " + doingIndex);
                    switch (childAt.getId()) {
                        case R.id.rl_one:
                            LogUtil.d("rl_one当前字view位置 = " + i);
                            numberBean = demoLocationList.get(0);
                            b = numberBean.isSelect();
                            LogUtil.d("第一个 是否选中 = " + b);
                            if (b) {
                                if (doingIndex == 1) {
                                    ImageView ivone = childAt.findViewById(R.id.iv_one);
                                    ivone.setBackgroundResource(R.mipmap.refresh);
                                    ivone.setVisibility(View.VISIBLE);
                                } else {
                                    ImageView ivone = childAt.findViewById(R.id.iv_one);
                                    ivone.setVisibility(View.GONE);
//                                    ivone.setBackgroundResource(R.mipmap.finish_icon);
                                }
                                childAt.setBackgroundResource(R.mipmap.home_circle_action);
                            } else {
                                childAt.setBackgroundResource(R.mipmap.home_circle);
                            }
                            break;
                        case R.id.rl_two:
                            LogUtil.d("rl_two当前字view位置 = " + i);
                            numberBean = demoLocationList.get(1);
                            b = numberBean.isSelect();
                            LogUtil.d("第二个 是否选中 = " + b);
                            if (b) {

                                if (doingIndex == 2) {
                                    ImageView ivone = childAt.findViewById(R.id.iv_two);
                                    ivone.setBackgroundResource(R.mipmap.refresh);
                                    ivone.setVisibility(View.VISIBLE);
                                } else {
                                    //小于2的 选中的 设置完成
                                    //finish_icon
                                    NumberBean numberBean1 = demoLocationList.get(1);
                                    boolean b1 = numberBean1.isSelect();
                                    LogUtil.d("第1个 是否选中 = " + b1);
//                                    if ((b1)) {
//                                        View childAt1 = circlelayout.getChildAt(1);
//                                        ImageView ivone = childAt1.findViewById(R.id.iv_one);
//                                        ivone.setBackgroundResource(R.mipmap.finish_icon);
//                                        ivone.setVisibility(View.VISIBLE);
//                                    }
                                    ImageView ivone = childAt.findViewById(R.id.iv_two);
//                                    ivone.setBackgroundResource(R.mipmap.finish_icon);
                                    ivone.setVisibility(View.GONE);
                                }
                                childAt.setBackgroundResource(R.mipmap.home_circle_action);
                            } else {
                                childAt.setBackgroundResource(R.mipmap.home_circle);
                            }
                            break;
                        case R.id.rl_three:
                            LogUtil.d("rl_three当前字view位置 = " + i);
                            numberBean = demoLocationList.get(2);
                            b = numberBean.isSelect();
                            LogUtil.d("第三个 是否选中 = " + b);
                            if (b) {
                                if (doingIndex == 3) {
                                    ImageView ivone = childAt.findViewById(R.id.iv_three);
                                    ivone.setBackgroundResource(R.mipmap.refresh);
                                    ivone.setVisibility(View.VISIBLE);
                                } else {

                                    //finish_icon
//                                    for (int j = 1; j < 3; j++) {
//                                        NumberBean numberBean1 = demoLocationList.get(j);
//                                        boolean b1 = numberBean1.isSelect();
//
//                                        LogUtil.d("第1个 是否选中 = " + b1);
//                                        if ((b1)) {
//                                            View childAt1 = circlelayout.getChildAt(j);
//                                            ImageView ivone = null;
//                                            if (j == 1) {
//                                                ivone = childAt1.findViewById(R.id.iv_one);
//                                            } else if (j == 2) {
//                                                ivone = childAt1.findViewById(R.id.iv_two);
//                                            }
//                                            if (ivone != null) {
//                                                ivone.setBackgroundResource(R.mipmap.finish_icon);
//                                                ivone.setVisibility(View.VISIBLE);
//                                            }
//                                        }
//                                    }

                                    ImageView ivone = childAt.findViewById(R.id.iv_three);
                                    ivone.setVisibility(View.GONE);

                                }
                                childAt.setBackgroundResource(R.mipmap.home_circle_action);
                            } else {
                                childAt.setBackgroundResource(R.mipmap.home_circle);
                            }
                            break;
                        case R.id.rl_four:
                            LogUtil.d("rl_four当前字view位置 = " + i);
                            numberBean = demoLocationList.get(3);
                            b = numberBean.isSelect();
                            LogUtil.d("第四个 是否选中背景 = " + b);
                            if (b) {
                                if (doingIndex == 4) {
                                    ImageView ivone = childAt.findViewById(R.id.iv_four);
                                    ivone.setBackgroundResource(R.mipmap.refresh);
                                    ivone.setVisibility(View.VISIBLE);
                                } else {
//                                    for (int j = 1; j < 4; j++) {
//                                        NumberBean numberBean1 = demoLocationList.get(j);
//                                        boolean b1 = numberBean1.isSelect();
//
//                                        if ((b1)) {
//                                            View childAt1 = circlelayout.getChildAt(j);
//                                            ImageView ivone = null;
//                                            if (j == 1) {
//                                                ivone = childAt1.findViewById(R.id.iv_one);
//                                            } else if (j == 2) {
//                                                ivone = childAt1.findViewById(R.id.iv_two);
//                                            } else if (j == 3) {
//                                                ivone = childAt1.findViewById(R.id.iv_three);
//                                            }
//                                            if (ivone != null) {
//                                                ivone.setBackgroundResource(R.mipmap.finish_icon);
//                                                ivone.setVisibility(View.VISIBLE);
//                                            }
//                                        }
//                                    }
                                    ImageView ivone = childAt.findViewById(R.id.iv_four);
                                    ivone.setVisibility(View.GONE);
                                }
                                childAt.setBackgroundResource(R.mipmap.home_circle_action);
                            } else {
                                childAt.setBackgroundResource(R.mipmap.home_circle);
                            }
                            break;
                    }
                    circlelayout.invalidate();
//                    LogUtil.d("childAt 更新  = " + childAt);
                }
            }
        }
//        int childCount = circlelayout.getChildCount();
//        LogUtil.d("子view = " + childCount);
    }


    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(spManager.getCurModle() == 1){
            updateModeText();
            if(bleManageUtil.isPlaying){
                if(!compareList())
                    bleManageUtil.createConfirmOrCancleData(1,demoLocationList);
            }
        }
        else{
            if(doingIndex > 0)
                updateCustomModeText(doingIndex);
            else{
                for (int i = 0; i < demoLocationList.size(); i++) {
                    NumberBean numberBean = demoLocationList.get(i);
                    boolean isSel = numberBean.isSelect();
                    LogUtil.d("第" + (i + 1) + "一个 是否选中 = " + isSel);
                    if (isSel) {
                        updateCustomModeText(i);
                        break;
                    }
                }
                updateCustomModeText(0);
            }
        }
        updateCircleLocation();
    }

    public boolean compareList(){
        for (int i = 0; i < demoLocationList.size(); i++) {
            Boolean b1 = demoLocationList.get(i).isSelect();
            Boolean b2 = runningDemoLocationList.get(i).isSelect();
            if(!b1.equals(b2))
                return false;
        }

        return true;
    }

    private void updateModeText() {
        if (BleManageUtil.getInstance().isConnect) {
            int group = spManager.getGroup();

            BleManageUtil.getInstance().getConfigDataFrame(group, new MyBleGattCallback() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onConfigSuccess(ConfigDataFram configDataFram) {
                    super.onConfigSuccess(configDataFram);
                    int time = configDataFram.getiTimeWork() / 10;
                    tvMode.setText("模式：" + configDataFram.getcGroupName()
                            + "   " + configDataFram.getiMotorSpeed()
                            + "转/秒" + "   时间: " + time + "s" +
                            configDataFram.getcClrModeHome()
                            + configDataFram.getInClearHome() +
                            configDataFram.getcClrSelectHome());
                }
            });
        } else {
            tvMode.setText("当前蓝牙未连接");
            ToastUtils.showCenter("当前蓝牙未连接");
        }
    }

    private void updateCustomModeText(int doingIndex) {
        if (BleManageUtil.getInstance().isConnect) {

            int group;
            if(doingIndex > 0)
                group = demoLocationList.get(doingIndex-1).getGroup();
            else
                group = demoLocationList.get(doingIndex).getGroup();


            String groupName = runTypelist.get(group).getName();

            BleManageUtil.getInstance().getConfigDataFrame(group, new MyBleGattCallback() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onConfigSuccess(ConfigDataFram configDataFram) {
                    super.onConfigSuccess(configDataFram);
                    int time = configDataFram.getiTimeWork() / 10;
                    tvMode.setText("模式：" + configDataFram.getcGroupName()
                            + "   " + configDataFram.getiMotorSpeed()
                            + "转/分" + "   时间: " + time + "s" +
                            configDataFram.getcClrModeHome()
                            + configDataFram.getInClearHome() +
                            configDataFram.getcClrSelectHome());
                }
            });
        } else {
            tvMode.setText("当前蓝牙未连接");
            ToastUtils.showCenter("当前蓝牙未连接");
        }
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.ll_play:
                //开启流程

                if(isWhisKnife || isWhisPipe || isChangeKnife){
                    if (BleManageUtil.getInstance().isPlaying) {
                        if(flow == 5){
                            stop();
                        }
                    }
                }else{
                    if (!demoLocationList.get(0).isSelect()) {
                        ToastUtils.showCenter("请选择样品座");
                        return;
                    }
                    if (!BleManageUtil.getInstance().isConnect) {
                        ToastUtils.showCenter("暂未连接蓝牙设备");
                        stop();
                        return;
                    }

                    if (BleManageUtil.getInstance().isPlaying) {
                        showCloseDialog();
                    } else {

                        if(spManager.getCurModle() == 1)
                            start();
                        else
                            startCustom();
                    }
                }
                break;
            case R.id.ll_bluetooch_setting:
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止");
                    return;
                }
                showBlueToochFragment();
                break;
            case R.id.bt_help:
                startActivity(HelpActivity.class);
                break;
            case R.id.bt_slect_parame:
                if (!BleManageUtil.getInstance().isConnect) {
                    ToastUtils.showCenter("暂未连接蓝牙设备");
                    stop();
                    return;
                }
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止设备");
                    return;
                }
                intent = new Intent();
                intent.setClass(mContext,SelectParameActivity.class);
                intent.putExtra("isDef",false);
                startActivity(intent);
                break;
            case R.id.tv_group_custom:
                if (!BleManageUtil.getInstance().isConnect) {
                    ToastUtils.showCenter("暂未连接蓝牙设备");
                    stop();
                    return;
                }
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止设备");
                    return;
                }
                startActivity(SelectCustomParameActivity.class);

                break;
            case R.id.tv_group_default:
                if (!BleManageUtil.getInstance().isConnect) {
                    ToastUtils.showCenter("暂未连接蓝牙设备");
                    stop();
                    return;
                }
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止设备");
                    return;
                }

                intent = new Intent();
                intent.setClass(mContext,SelectParameActivity.class);
                intent.putExtra("isDef",true);
                startActivity(intent);
                break;
            case R.id.tv_changee_knife:
                if (!BleManageUtil.getInstance().isConnect) {
                    ToastUtils.showCenter("暂未连接蓝牙设备");
                    stop();
                    return;
                }
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止设备");
                    return;
                }
                showChangeKnifeDialog("请先拆除所有样品罐");
                break;
            case R.id.tv_loop_num:
                if (!BleManageUtil.getInstance().isConnect) {
                    ToastUtils.showCenter("暂未连接蓝牙设备");
                    stop();
                    return;
                }
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止设备");
                    return;
                }
                startActivity(SelectLoopNumActivity.class);
                break;
            case R.id.tv_wish_pipe:
                if (!BleManageUtil.getInstance().isConnect) {
                    ToastUtils.showCenter("暂未连接蓝牙设备");
                    stop();
                    return;
                }
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止设备");
                    return;
                }
                showWhisPipeDialog("清洗管路");
                break;
            case R.id.tv_wish_knife:
                if (!BleManageUtil.getInstance().isConnect) {
                    ToastUtils.showCenter("暂未连接蓝牙设备");
                    stop();
                    return;
                }
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止设备");
                    return;
                }
                showWhisDialog("清洗转刀");
                break;
        }
    }


    private void start() {

        loopNum = spManager.getLoopNum();
        if(loopNum > 1){
            isLoop = true;
        }else{
            isLoop = false;
        }

        PushLog.info("连续模式开始研磨   是否循环 "+isLoop + "  loopNum = "+loopNum);

        runningDemoLocationList.clear();
        for (NumberBean bean : demoLocationList) {
            runningDemoLocationList.add(bean);
        }

        //开启设备
        locationList = spManager.getLocationList();
        demoLocationList = GsonUtil.jsonToList(locationList, NumberBean.class);
        BleManageUtil.getInstance().beginDevices(1,spManager.getGroup(),demoLocationList);

        iv_group_state.setVisibility(View.VISIBLE);

        ivPlayState.setBackgroundResource(R.mipmap.stop);
        selectState();
    }

    private void startCustom() {

        loopNum = spManager.getLoopNum();
        if(loopNum > 1){
            isLoop = true;
        }else{
            isLoop = false;
        }

        PushLog.info("自定义模式开始研磨   是否循环 "+isLoop  + "  loopNum = "+loopNum);

        runningDemoLocationList.clear();
        for (NumberBean bean : demoLocationList) {
            runningDemoLocationList.add(bean);
        }


        //开启设备
        locationList = spManager.getLocationList();
        demoLocationList = GsonUtil.jsonToList(locationList, NumberBean.class);
        BleManageUtil.getInstance().beginDevicesForCustom(1,demoLocationList);

        iv_group_custom_state.setVisibility(View.VISIBLE);

        ivPlayState.setBackgroundResource(R.mipmap.stop);
        selectState();
    }
    private void startWhishknife() {

        BleManageUtil.getInstance().wishKnife();

        runWishTimer();
        tvMode.setText("模式：清洗转刀");
    }

    private void startWhishPipe() {

        BleManageUtil.getInstance().wishPipe();

        runWishTimer();
        tvMode.setText("模式：清洁管路");
    }
    private void startChangeKnife() {

        BleManageUtil.getInstance().changeKnife();

        runWishTimer();
        tvMode.setText("模式：更换/清理转刀");
    }

    //这是定时器
    public void runWishTimer() {
        LogUtil.d("runTimer启动定时器开始");
        if (timer != null) {
            LogUtil.d("启动定时器 失败 timer != null");
            return;
        }
        LogUtil.d("启动定时器 number = ");
        if (bleManageUtil != null && BleManageUtil.getInstance().isConnect) {
            LogUtil.d("启动定时器 number = ");
            timer = new CountDownTimer(Long.MAX_VALUE, 2000) {
                @Override
                public void onFinish() {
                    cancel();
                }

                @Override
                public void onTick(long millisUntilFinished) {
                    getDeviceState();
                }
            }.start();
        }
    }

    private void showWhisDialog(String msg) {
        AlertView mAlertView = new AlertView("", msg, "取消", new String[]{"确认"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    isWhisKnife = true;
                    BleManageUtil.getInstance().isPlaying = true;
                    tv_wish_knife.setPressed(true);
                    tv_wish_knife.setEnabled(false);
                    startWhishknife();
                } else if (position == -1) {
//                    ToastUtils.showCenter("取消");
//                    submit(1);
                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }

    private void showWhisPipeDialog(String msg) {
        AlertView mAlertView = new AlertView("", msg, "取消", new String[]{"确认"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    isWhisPipe = true;
                    BleManageUtil.getInstance().isPlaying = true;
                    tv_wish_pipe.setPressed(true);
                    tv_wish_pipe.setEnabled(false);
                    startWhishPipe();
                } else if (position == -1) {
//                    ToastUtils.showCenter("取消");
//                    submit(1);
                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }
    private void showChangeKnifeDialog(String msg) {
        AlertView mAlertView = new AlertView("", msg, "取消", new String[]{"确认"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    isChangeKnife = true;
                    BleManageUtil.getInstance().isPlaying = true;
                    tv_changee_knife.setPressed(true);
                    tv_changee_knife.setEnabled(false);
                    startChangeKnife();
                } else if (position == -1) {
//                    ToastUtils.showCenter("取消");
//                    submit(1);
                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }
    private void showOffPowerDialog(String msg) {
        AlertView mAlertView = new AlertView("", msg, "取消", new String[]{"确认"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {

                } else if (position == -1) {

                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }

    private void showErrorStopDialogOne(String message) {
        errorDialogShow = true;
        AlertView mAlertView = new AlertView("", message, null, new String[]{"确认"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    //确认是继续

                } else if (position == -1) {
                    //取消是停止

                }
                errorDialogShow = false;
            }
        }).setCancelable(false);
        mAlertView.show();
    }


    private void stop() {

        if(isWhisKnife){
            tv_wish_knife.setPressed(false);
            tv_wish_knife.setEnabled(true);
            isWhisKnife = !isWhisKnife;
        }
        if(isWhisPipe){
            tv_wish_pipe.setPressed(false);
            tv_wish_pipe.setEnabled(true);
            isWhisPipe = !isWhisPipe;
        }
        if(isChangeKnife){
            tv_changee_knife.setPressed(false);
            tv_changee_knife.setEnabled(true);
            isChangeKnife = !isChangeKnife;
        }

        if(isLoop){
            curLoopNum = 1;
            isLoop = false;
        }
        //初始化研磨罐状态
        for (int i = 0; i < demoLocationList.size(); i++) {
            demoLocationList.get(i).setSelect(false);
        }
        spManager.saveLocationList(GsonUtil.gsonString(demoLocationList));

        cancle();

        iv_group_custom_state.setVisibility(View.GONE);
        iv_group_state.setVisibility(View.GONE);

        ivPlayState.setBackgroundResource(R.mipmap.play);
        circlelayout.setCircleText("停止工作");
        tvMode.setText("已停止运行");
        PushLog.info("stop  停止工作 初始化研磨罐状态");
        updateCircleLocation();
        timeStop();
        //soundPlayer.play(R.raw.didi, false);

        BleManageUtil.getInstance().stopDevices();
    }


    private void selectState() {
        runDymCodeTimer();
        timeRestart();
    }

    private void showBlueToochFragment() {
        if (myDialogFragment == null) {
            myDialogFragment = MyDialogFragment.newInstance(0);
            myDialogFragment.setInterface(new MyDialogFragment.Mydialoginterface() {
                @Override
                public void cancel() {
                    LogUtil.d("cancel");
                }

                @Override
                public void dismiss() {

                }
            });
        }
        myDialogFragment.show(getSupportFragmentManager(), "bluetoch");
    }

    //这是定时器
    public void runDymCodeTimer() {
//        getDymCode();//先请求一次二维码
        LogUtil.d("runTimer启动定时器开始");
        if (timer != null) {
            LogUtil.d("启动定时器 失败 timer != null");
//            timer.cancel();
            return;
        }
        LogUtil.d("启动定时器 number = ");
        if (bleManageUtil != null && BleManageUtil.getInstance().isConnect) {
            LogUtil.d("启动定时器 number = ");
//            number = spm.getCurrentCardInfo().getEcardNo();
            timer = new CountDownTimer(Long.MAX_VALUE, 2500) {
                @Override
                public void onFinish() {
                    cancel();
                }

                @Override
                public void onTick(long millisUntilFinished) {
//                    LogUtil.d("CountDownTimer定时器执行获取设备状态" + millisUntilFinished);
//                createCode();
                    if (bleManageUtil != null && BleManageUtil.getInstance().isConnect) {
                        getDeviceState();
                        //PushLog.info("getDeviceState 获取设备状态  运行状态 = "+bleManageUtil.isPlaying);
                    }
                }
            }.start();
        }
    }

    //这个方法可以在activity或者fragment销毁的时候调用，防止内存泄漏
    public void cancle() {
        if (timer != null) {
//            LogUtil.d("取消定时器");
            timer.cancel();
            timer = null;
        }
    }

    MyBleDeviceStateCallBack myBleDeviceStateCallBack = null;


    int oldState = 0;

    /**
     * 获取设备状态
     */
    private void getDeviceState() {
        /**
         * Flow
         * 0x01 位置初始化
         * 0x02 定位流程
         * 0x03 超声波清洗
         * 0x04 热风烘干
         * 0x05 清水清洗
         * 0x06 研磨工作
         *
         * 正常流程结束，Flow = 0x06， Step = 0xA0.
         * 指令结束流程，Flow = 0x10， Step = 0xA0.
         * 异常结束流程，Flow = 0x10， Step = 0xA0.
         */
        if (myBleDeviceStateCallBack == null) {
            myBleDeviceStateCallBack = new MyBleDeviceStateCallBack() {

                @Override
                public void onDevicesState(DeviceStateFram deviceStateFram) {

                    //{name=1, Flow=6, Step=0, DataDev=0}
                    flow = deviceStateFram.getFlow();
                    int step = deviceStateFram.getStep();
                    LogUtil.d("errorDialogShow = " + errorDialogShow);

                    dataDev = deviceStateFram.getDataDev();
                    name = deviceStateFram.getName();
                    LogUtil.i(" 当前设备状态 = " + GsonUtil.gsonString(deviceStateFram));
                    PushLog.info(" 当前设备状态 = " + GsonUtil.gsonString(deviceStateFram));

                    //E0-Ef
                    if (225 <= step  && step<= 240) {
                        if (!errorDialogShow) {
                            stop();
                            showErrorStopDialogOne("设备异常e0");
                            return;
                        }
                    }


                    switch (flow) {
                        case 0:
                            circlelayout.setCircleText("设备已停止");
                            doingIndex = -1;
                            updateCircleLocation();
                            ivPlayState.setBackgroundResource(R.mipmap.play);
                            bleManageUtil.isPlaying = false;
                            PushLog.info("设备已停止  运行状态 = "+bleManageUtil.isPlaying);

                            if(isWhisKnife){
                                tv_wish_knife.setPressed(false);
                                tv_wish_knife.setEnabled(true);
                                isWhisKnife = !isWhisKnife;
                            }
                            if(isWhisPipe){
                                tv_wish_pipe.setPressed(false);
                                tv_wish_pipe.setEnabled(true);
                                isWhisPipe = !isWhisPipe;
                            }
                            if(isChangeKnife){
                                tv_changee_knife.setPressed(false);
                                tv_changee_knife.setEnabled(true);
                                isChangeKnife = !isChangeKnife;
                            }

                            break;
                        case 1:
                            circlelayout.setCircleText("位置初始化中");
                            doingIndex = -1;
                            updateCircleLocation();
                            ivPlayState.setBackgroundResource(R.mipmap.stop);
                            bleManageUtil.isPlaying = true;
                            PushLog.info("位置初始化中 运行状态 = "+bleManageUtil.isPlaying);
                            break;
                        case 3:
                            //超声波清洗
                            circlelayout.setCircleText("超声波清洗中");
                            doingIndex = -1;
                            updateCircleLocation();
                            ivPlayState.setBackgroundResource(R.mipmap.stop);
                            bleManageUtil.isPlaying = true;
                            PushLog.info("超声波清洗中 运行状态 = "+bleManageUtil.isPlaying);
                            //E1 是出错
                            if (225 == step) {
                                if (!errorDialogShow) {
                                    showErrorDialogOne("超声波清洗错误,请检查供水");
                                    PushLog.info("超声波清洗错误,请检查供水 运行状态 = "+bleManageUtil.isPlaying);
                                }
                            }
                            break;
                        case 4:
                            //烘干位
                            circlelayout.setCircleText("烘干中");
                            doingIndex = -1;
                            updateCircleLocation();
                            ivPlayState.setBackgroundResource(R.mipmap.stop);
                            bleManageUtil.isPlaying = true;
                            PushLog.info("烘干中 运行状态 = "+bleManageUtil.isPlaying);
                            break;
                        case 5:
                            ivPlayState.setBackgroundResource(R.mipmap.stop);
                            bleManageUtil.isPlaying = true;
                            doingIndex = -1;
                            //清水清洗
                            circlelayout.setCircleText("清水清洗中");
                            PushLog.info("清水清洗中 运行状态 = "+bleManageUtil.isPlaying);
                            updateCircleLocation();

                            //E1 是出错
                            if (225 == step) {
                                if (!errorDialogShow) {
                                    showErrorDialogOne("清水清洗错误,请检查供水");
                                    PushLog.info("清水清洗错误,请检查供水 运行状态 = "+bleManageUtil.isPlaying);
                                }
                            }
                            break;
                        case 6:
                            ivPlayState.setBackgroundResource(R.mipmap.stop);
                            bleManageUtil.isPlaying = true;
                            LogUtil.i("研磨中 flow = 6  dataDev= " + dataDev + " getStep = " + deviceStateFram.getStep());
                            PushLog.info("研磨中 flow = 6  样品dataDev= " + dataDev + " getStep = " + deviceStateFram.getStep()+
                                    " 运行模式 name = " + name+
                                    "   运行状态 = "+bleManageUtil.isPlaying);
                            //0x06工 作流程 正在研磨
                            doingIndex = dataDev;
                            updateCircleLocation();
                            if(name == 7)
                                updateCustomModeText(doingIndex);
                            else
                                updateModeText();
                            LogUtil.i("doingIndex = " + doingIndex + "  oldDoingIndex = " + oldDoingIndex);
//                            doingIndex
                            circlelayout.setCircleText("研磨中" + " 样品" + dataDev);
                            if (deviceStateFram.getStep() == 160) {
                                //stop();
                            }
                            if (step == 229) {
                                if (!errorDialogShow) {
                                    showErrorDialog("当前设备停止,确认后取下样品灌");
                                    PushLog.info("当前设备停止,确认后取下样品灌 运行状态 = "+bleManageUtil.isPlaying);
                                }
                                return;
                            }
                            if (step == 230) {
                                if (!errorDialogShow) {
                                    showErrorDialog("当前设备停止,确认后清理刀头残留物");
                                    PushLog.info("当前设备停止,确认后清理刀头残留物 运行状态 = "+bleManageUtil.isPlaying);
                                }
                                return;
                            }


                            break;

                        case 10:
                            LogUtil.i("研磨中 flow = 6  dataDev= " + dataDev + " getStep = " + deviceStateFram.getStep());
                            PushLog.info("研磨中 flow = 6  dataDev= " + dataDev + " getStep = " + deviceStateFram.getStep());
                            //0x10工 作流程 停止
                            doingIndex = -1;
//                            updateCircleLocation();
                            LogUtil.i("doingIndex = " + doingIndex + "  oldDoingIndex = " + oldDoingIndex);
//                            doingIndex
                            if (deviceStateFram.getStep() == 160) {
                                cancle();
                                ivPlayState.setBackgroundResource(R.mipmap.play);
                                bleManageUtil.isPlaying = false;
                                circlelayout.setCircleText("停止工作");
                                PushLog.info("当前设备停止工作 运行状态 = "+bleManageUtil.isPlaying);
                                updateCircleLocation();
                                timeStop();
                                //soundPlayer.play(R.raw.didi, false);
//                                ToastUtils.showCenter("停止工作");
//                                BleManageUtil.getInstance().stopDevices();
//                                if (!errorDialogShow) {
//
//                                    showErrorDialog("当前设备停止,是否继续");
//                                }
                            }
//                        case 16:
//                            LogUtil.d("研磨中 flow = 6  dataDev= " + dataDev + " getStep = " + deviceStateFram.getStep());
//                            //0x10工 作流程 停止
//                            doingIndex = -1;
////                            updateCircleLocation();
//                            LogUtil.d("doingIndex = " + doingIndex + "  oldDoingIndex = " + oldDoingIndex);
////                            doingIndex
//
//                            break;
                    }

                    if (deviceStateFram.getStep() == 160) {
                        bleManageUtil.isPlaying = false;
                        if(isWhisKnife){
                            tv_wish_knife.setPressed(false);
                            tv_wish_knife.setEnabled(true);
                            isWhisKnife = !isWhisKnife;
                        }
                        if(isWhisPipe){
                            tv_wish_pipe.setPressed(false);
                            tv_wish_pipe.setEnabled(true);
                            isWhisPipe = !isWhisPipe;
                        }
                        if(isChangeKnife){
                            tv_changee_knife.setPressed(false);
                            tv_changee_knife.setEnabled(true);
                            isChangeKnife = !isChangeKnife;
                            showOffPowerDialog("操作刀头前请先关闭电源");
                        }

                        if(isLoop){
                            LogUtil.i(" 当前设备状态 循环状态  loopNum ：" + loopNum +"    curLoopNum ："+curLoopNum);
                            PushLog.info(" 当前设备停止工作  备状态 循环状态  loopNum ：" + loopNum +"    curLoopNum ："+curLoopNum);
                            if(curLoopNum == loopNum){
                                LogUtil.i(" 当前设备状态 循环状态  结束 ：" + loopNum +"    curLoopNum ："+curLoopNum);
                                PushLog.info(" 当前设备停止工作  设备状态 循环状态  结束 ：" + loopNum +"    curLoopNum ："+curLoopNum);
                                stop();
                                return;
                            }
                            showConnectDialog("请更换样品");
                        }else{
                            LogUtil.i(" 当前设备状态 单次 ");
                            PushLog.info(" 当前设备停止工作  设备状态 单次 ");
                            stop();
                        }

                        cancle();
                        ivPlayState.setBackgroundResource(R.mipmap.play);
                        circlelayout.setCircleText("停止工作");

                        updateCircleLocation();
                        timeStop();
                        //soundPlayer.play(R.raw.didi, false);
                        ToastUtils.showCenter("停止工作");
                        PushLog.info("当前设备停止工作 运行状态 = "+bleManageUtil.isPlaying);
                    }
                }

                @Override
                public void onFail() {
                    /*for (int i = 0; i < demoLocationList.size(); i++) {
                        demoLocationList.get(i).setSelect(false);
                    }
                    spManager.saveLocationList(GsonUtil.gsonString(demoLocationList));
                    updateCircleLocation();*/
                }
            };
        }

        BleManageUtil.getInstance().readDevicesState(myBleDeviceStateCallBack);


    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long secondTime = System.currentTimeMillis();
            boolean isFinish = false;

            if (!isFinish) {
                if (secondTime - firstTime > 2000) {
                    Toast.makeText(MyApplication.application, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;
                    return true;
                } else {
//                    AppManager.getAppManager().finishAllActivity();
                    return super.onKeyDown(keyCode, event);
                }
            } else {
                return false;
            }
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }


    /**
     * 申请运行时权限，不授予会搜索不到设备
     */
    private void initPermissions() {
        if (ContextCompat.checkSelfPermission(this, "android.permission-group.LOCATION") != 0) {
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{
                            "android.permission.ACCESS_FINE_LOCATION",
                            "android.permission.ACCESS_COARSE_LOCATION",
                            "android.permission.ACCESS_WIFI_STATE"},
                    1
            );
        }
    }


    @Override
    public Resources getResources() {
        //需要升级到 v1.1.2 及以上版本才能使用 AutoSizeCompat
        AutoSizeCompat.autoConvertDensityOfGlobal((super.getResources()));//如果没有自定义需求用这个方法
//        AutoSizeCompat.autoConvertDensity((super.getResources(),667, false);//如果有自定义需求就用这个方法
        return super.getResources();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ObserverManager.getInstance().deleteObserver(this);
        //LOGSDKManager.getInstance().destroy();
        bleManageUtil.getHandle().removeCallbacksAndMessages(null);
    }

    @Override
    public void disConnected(BleDevice bleDevice) {
        //断开连接
        tvMode.setText("蓝牙已断开");
        ToastUtils.showCenter("是否重新连接");
        showConnectDialog("连接已断开,是否重新连接?", bleDevice);

    }

    @Override
    public void onConnected(BleDevice bleDevice) {
        tvMode.setText("蓝牙已连接");
        selectState();//连接成功后读取状态
        //PushLog.info("蓝牙已连接 连接成功后读取设备状态 运行状态 = "+bleManageUtil.isPlaying);
        if(mHistoryAlertView != null){
            if(mHistoryAlertView.isShowing())
                mHistoryAlertView.dismiss();
        }
    }

    private void showHistoryConnectDialog(String msg, final BleDevice bleDevice) {
        if(mHistoryAlertView == null){
            mHistoryAlertView = new AlertView("", msg, "取消", new String[]{"连接"},
                    null, this, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    if (position == 0) {
//                    submit(0);
                        ToastUtils.showCenter("正在重新连接");
                        BleManageUtil.getInstance().connect(bleDevice);
                    } else if (position == -1) {
//                    ToastUtils.showCenter("取消");
//                    submit(1);
                    }
                }
            }).setCancelable(false);
        }
        mHistoryAlertView.show();
    }

    private void showCloseDialog() {
        AlertView mAlertView = new AlertView("", "是否停止运行", "取消", new String[]{"停止"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
//                    submit(0);
                    ToastUtils.showCenter("停止");
                    stop();
                } else if (position == -1) {
                    ToastUtils.showCenter("取消");
//                    submit(1);
                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }

    private boolean errorDialogShow = false;

    private void showErrorDialogOne(String message) {
        errorDialogShow = true;
        AlertView mAlertView = new AlertView("", message, null, new String[]{"确认"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    //确认是继续
                    BleManageUtil.getInstance().writeDeviceKeyFrame(1);
                    ToastUtils.showCenter("正在继续");
                } else if (position == -1) {
                    //取消是停止
//                    ToastUtils.showCenter("正在停止");
//                    BleManageUtil.getInstance().writeDeviceKeyFrame(0);
//                    ToastUtils.showCenter("取消");
//                    submit(1);
                }
                errorDialogShow = false;
            }
        }).setCancelable(false);
        mAlertView.show();
    }

    private void showErrorDialog(String message) {
        errorDialogShow = true;
        AlertView mAlertView = new AlertView("", message, "停止", new String[]{"继续"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    //确认是继续
                    BleManageUtil.getInstance().writeDeviceKeyFrame(1);
                    ToastUtils.showCenter("正在继续");
                } else if (position == -1) {
                    //取消是停止
                    ToastUtils.showCenter("正在停止");
                    BleManageUtil.getInstance().writeDeviceKeyFrame(0);
//                    ToastUtils.showCenter("取消");
//                    submit(1);
                }
                errorDialogShow = false;
            }
        }).setCancelable(false);
        mAlertView.show();
    }


    private void showConnectDialog(String msg, final BleDevice bleDevice) {
        AlertView mAlertView = new AlertView("", msg, "取消", new String[]{"连接"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
//                    submit(0);
                    ToastUtils.showCenter("正在重新连接");
                    BleManageUtil.getInstance().connect(bleDevice);
                } else if (position == -1) {
//                    ToastUtils.showCenter("取消");
//                    submit(1);
                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }

    private void showConnectDialog(String msg) {
        AlertView mAlertView = new AlertView("", msg, "停止", new String[]{"继续"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    curLoopNum++;
                    if(spManager.getCurModle() == 1)
                        start();
                    else
                        startCustom();
                } else if (position == -1) {
                    stop();
                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }

    //蓝牙操作;======================================================


}